var lastAngle;
var lastInteraction;
var sensitive = 0.2;
var closed = true;
var windowWidth = window.innerWidth-100;
var windowHeight = window.innerHeight;
var maxSize = 100;
var minSize = 40;
var maxFingers = 5;
var linearMove = 1;

function rotateTable(angleX,angleY)
{
	var angleString = "rotateX("+(angleX*maxAngle)+"deg) rotateY("+(angleY*maxAngle)+"deg) translateZ(-200px)";
	var transString = " translate3d("+(angleX*linearMove)+"px,"+(angleY*linearMove)+"px,-200px)";
	//angleString+=transString;
	if(angleString!=lastAngle)
	{
		if(angleX<(-1*sensitive))
		{
			if(users[POSBOTTOM]!=null)
			{
				console.debug('bottom');
				
				world.DestroyBody(walls[1]);
				walls[1] = null;
				closed = false;
				
			}
			document.getElementById('doorSound').play();
		}
		else if(angleX>(sensitive))
		{
			if(users[POSTOP]!=null)
			{
				console.debug('top');
				world.DestroyBody(walls[0]);
				walls[0] = null;
				closed = false;
			}
			document.getElementById('doorSound').play();
		}
		else if(angleY<(-1*sensitive))
		{
			if(users[POSLEFT]!=null)
			{
				console.debug('left');
				world.DestroyBody(walls[2]);
				walls[2] = null;
				closed = false;

			}
			document.getElementById('doorSound').play();
		}
		else if(angleY>(sensitive))
		{
			if(users[POSRIGHT]!=null)
			{

				console.debug('right');
				
				world.DestroyBody(walls[3]);
				walls[3] = null;
				closed = false;
				
			}
			document.getElementById('doorSound').play();
		}
		else
		{
			if(!closed)
			{
				setWalls();
				closed = true;
			}
		}
		document.getElementById("box").style.webkitTransform = angleString;
		changeGravity(angleY*maxAngle,-angleX*maxAngle);
	}
	lastAngle = angleString;
}

function sendEvent(name,data)
{
	if(name=="deviceorientation")
	{
		var event = document.createEvent("DeviceOrientationEvent");
		event.initDeviceOrientationEvent(name, true, true, data["alpha"], data["beta"], data["gamma"]);
		window.dispatchEvent(event);
	}
	else if(name=="touchstart"||name=="touchmove"||name=="touchend")
	{
		var event = document.createEvent("MouseEvents");
		event.initMouseEvent(name, true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, document);
		event.touches = data["touches"];
		event.targetTouches = data["touches"];
		event.changedTouches = data["touches"];
		document.dispatchEvent(event);
	}
}

function drawEventInclination(data)
{
	if(data["Status"]=="START")
	{
	}
	else if(data["Status"]=="OVER")
	{
		if(onVirtualAccelerometer)
		{
			var eventData = {};
			eventData["alpha"] = 0;
			eventData["beta"] = data["Data"]["Angles"]["Y"]*maxAngle;
			eventData["gamma"] = data["Data"]["Angles"]["X"]*maxAngle;
			sendEvent("deviceorientation",eventData);
		}
		else
		{
			rotateTable(data["Data"]["Angles"]["X"],data["Data"]["Angles"]["Y"]);
		}
	}
	else if(data["Status"]=="END")
	{
	}
}

function drawEvent(data)
{
	if(data["Data"]["EventType"] == "INCLINATION")
	{
		drawEventInclination(data["Data"]["EventData"]);
	}
}

function drawInteractionFingers(data)
{
	if(data["Data"]["Status"]!="END")
	{
		var fingers = data["Data"]["Fingers"];
		for(var i=0;i<maxFingers;i++)
		{
			if(typeof fingers[i] != 'undefined')
			{
				document.getElementById("finger"+fingers[i]["FingerNumber"]).style.display = "block";
				document.getElementById("finger"+fingers[i]["FingerNumber"]).style.left = ((windowWidth/2)+(fingers[i]["Points"]["X"]*windowWidth))+"px";
				document.getElementById("finger"+fingers[i]["FingerNumber"]).style.top = ((windowHeight/2)-(fingers[i]["Points"]["Y"]*windowHeight))+"px";
				document.getElementById("finger"+fingers[i]["FingerNumber"]).style.minWidth = document.getElementById("finger"+fingers[i]["FingerNumber"]).style.minHeight = minSize + (fingers[i]["Points"]["Z"]*maxSize)+"px";
			}
			else
			{
				document.getElementById("finger"+(i+1)).style.display = "none";
			}
		}
	}
	else
	{
		for(var i=1;i<=maxFingers;i++)
		{
			document.getElementById("finger"+i).style.display = "none";
		}
	}
}

function drawInteraction(data)
{
	if(onVirtualMultiTouch)
	{
		var eventName;
		if(data["Data"]["Status"]=="START")
		{
			eventName = "touchstart";
		}
		else if(data["Data"]["Status"]=="OVER")
		{
			eventName = "touchmove";
		}
		else if(data["Data"]["Status"]=="END")
		{
			eventName = "touchend";
		}
		var arrFingers = [];
		var fingers = data["Data"]["Fingers"];
		var listString = "document.createTouchList(";
		coma = "";
		for(var i in fingers)
		{
			var valX = (windowWidth/2)+(fingers[i]["Points"]["X"]*windowWidth);
			var valY = (windowHeight/2)-(fingers[i]["Points"]["Y"]*windowHeight);
			var valZ = minSize + (fingers[i]["Points"]["Z"]*maxSize);
			var touchObj = document.createTouch(window, document, (new Date()).getTime(), valX, valY, valX, valY, valX, valY, valZ, valZ, valZ, valZ);
			console.debug(touchObj);
			arrFingers.push(touchObj);
			listString += coma + "arrFingers[" + i + "]";
			coma = ",";
		}
		listString += ")";
		console.debug(arrFingers);
		//var listFingers = document.createTouchList(arrFingers);
		var listFingers = eval(listString);
		console.debug(listFingers);
		sendEvent(eventName,{"touches":listFingers});
	}
	else
	{
		drawInteractionFingers(data);
	}
}

function onDebug(request)
{
	console.debug(request["data"]);
}

function onConnected(request)
{
	console.debug("Connected");
	//worker.postMessage({"method":"suscribeGroup","user":""});
	worker.postMessage({"method":"suscribeStream","user":""});
}

function onMessage(request)
{
	//console.debug(request["data"]);
}

function onInteraction(request)
{
	//console.debug("Interaction");
	//console.debug(request["data"]);
	drawInteraction(request["data"]);
}

function onEvent(request)
{
	drawEvent(request["data"]);
}

function onDisconnected(request)
{
	console.debug("Disconnected");
}

function onDriverResponse(event)
{
	var request = event.data;
	if(request["method"]=="onDebug")
		onDebug(request);
	else if(request["method"]=="onConnected")
		onConnected(request);
	else if(request["method"]=="onMessage")
		onMessage(request);
	else if(request["method"]=="onInteraction")
		onInteraction(request);
	else if(request["method"]=="onEvent")
		onEvent(request);
	else if(request["method"]=="onDisconnected")
		onDisconnected(request);
//document.getElementById('result').textContent = "Worker Said: "+event.data;
}

function onDriverError(event)
{
}